package com.rich.dmr.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rich.dmr.DmrApplication;
import com.rich.dmr.R;
import com.rich.dmr.service.DmrService;
import com.rich.dmr.ui.view.SimpleToolbar;
import com.rich.dmr.utils.Constant;
import com.rich.dmr.utils.DataBaseUtils;
import com.rich.dmr.utils.SoundPoolUtils;

import java.util.Arrays;

import rich.dmr.DmrManager;

public class MainActivity extends BaseActivity implements View.OnClickListener, View.OnTouchListener {

    private String TAG = "rich---MainActivity";

    private DmrManager dmrManager;
    private SimpleToolbar simpleToolbar;
    private TextView tvContact;
    private TextView tvCallType;
    private Intent intent = new Intent();
    private SharedPreferences mSp;
    private boolean isHeadSet;
    private long firstTime = 0;

    @SuppressLint({"WrongConstant", "ClickableViewAccessibility"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dmrManager = (DmrManager) getSystemService("dmrservice");
        simpleToolbar = findViewById(R.id.main_tools_bar);
        simpleToolbar.setLeftTitleClickListener(this);
        simpleToolbar.setLeftTitleDrawable(R.mipmap.rich_logo);
        simpleToolbar.setLeftTitleText(getString(R.string.app_name_rich));
        simpleToolbar.setLeftTextSize(25);
        LinearLayout mainMenu = findViewById(R.id.main_menu_settings);
        mainMenu.setOnClickListener(this);

        LinearLayout groupList = findViewById(R.id.main_group_list);
        groupList.setOnClickListener(this);

        LinearLayout singleCall = findViewById(R.id.main_single_call);
        singleCall.setOnClickListener(this);

        LinearLayout pttCall = findViewById(R.id.ptt_call_bt);
        pttCall.setOnClickListener(this);
        pttCall.setOnTouchListener(this);

        tvContact = findViewById(R.id.call_contact);
        tvCallType = findViewById(R.id.call_type);

        mSp = getSharedPreferences(Constant.sp_key, Context.MODE_PRIVATE);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_SET_COMMAND_STATE);
        intentFilter.addAction(Constant.ACTION_MODULE_STATE);
        intentFilter.addAction(Constant.ACTION_VERSION_INFO);
        intentFilter.addAction(Constant.ACTION_SIGNAL_INFO);
        intentFilter.addAction(Constant.ACTION_INBOUND_TYPE);
        intentFilter.addAction(Constant.ACTION_TRANSMITTER_LOCAL_ID);
        intentFilter.addAction(Constant.ACTION_INBOUND_NUMBER);
        intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);

        registerReceiver(broadcastReceiver, intentFilter);

        if (dmrManager != null) {
            //if (dmrManager.getMode() != 0) {
                dmrManager.setMode(0);
            //}
        }
        SharedPreferences.Editor mEditor = mSp.edit();
        mEditor.putBoolean("shutdown_app", false);
        mEditor.apply();

        Intent intent = new Intent();
        intent.setClass(this, DmrService.class);
        startForegroundService(intent);
        //startService(intent);
        boolean isInitData = mSp.getBoolean("init_db",false);
        if(!isInitData){
            DataBaseUtils.getInstance(this).insertChannel(1,409750000,409750000);
            DataBaseUtils.getInstance(this).insertChannel(2,408750000,408750000);
            DataBaseUtils.getInstance(this).insertChannel(3,407750000,407750000);
            DataBaseUtils.getInstance(this).insertChannel(4,406750000,406750000);
            mEditor.putBoolean("init_db", true);
            mEditor.apply();
        }
        DmrApplication.getInstance().addActivity(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_menu_settings:
                intent.setClass(this, SettingsActivity.class);
                startActivity(intent);
                break;
            case R.id.ptt_call_bt:

                break;
            case R.id.main_group_list:
                intent.setClass(this, GroupListActivity.class);
                startActivity(intent);
                break;
            case R.id.main_single_call:
                intent.setClass(this, DialingActivity.class);
                startActivity(intent);
                overridePendingTransition(0, 0);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateInfo();
    }

    @SuppressLint("SetTextI18n")
    public void updateInfo() {
        boolean isShowId = mSp.getBoolean(Constant.showLocalId, true);
        if (dmrManager != null) {
            tvContact.setText(dmrManager.getTransmitContact() + "");
            switch (dmrManager.getContactType()) {
                case 0:
                    tvCallType.setText(getString(R.string.call_single));
                    break;
                case 1:
                    tvCallType.setText(getString(R.string.call_group));
                    if(!Arrays.asList(dmrManager.getGroupList().split("/")).contains(String.valueOf(dmrManager.getTransmitContact()))){
                        dmrManager.setTransmitContact(1);
                        dmrManager.flush();
                        tvContact.setText("");
                        tvCallType.setText("select group");
                    }
                    break;
                case 2:
                    tvCallType.setText(getString(R.string.call_all));
                    break;
            }
            if (isShowId) {
                simpleToolbar.setRightTitleText(dmrManager.getLocalId() + "");
            } else {
                simpleToolbar.setRightTitleText("");
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (dmrManager != null) {
                    if (isHeadSet) {
                        dmrManager.setHeadSetMic(1);
                    }
                    dmrManager.sendDmrPTT(true);
                }
                break;
            case MotionEvent.ACTION_MOVE:
                Log.d(TAG, "onTouchEvent move");
                break;
            case MotionEvent.ACTION_UP:
                if (dmrManager != null) {
                    if (isHeadSet) {
                        dmrManager.setHeadSetMic(2);
                    }
                    dmrManager.sendDmrPTT(false);
                }
                break;
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
        Log.d(TAG, "onDestroy");
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onReceive(Context context, Intent intent) {

            Log.d(TAG, "action="+intent.getAction());

           if (Constant.ACTION_SET_COMMAND_STATE.equals(intent.getAction())) {
                int setState = intent.getIntExtra(Constant.EXTRA_RESPONSE_DATA, -1);
            } else if (Constant.ACTION_MODULE_STATE.equals(intent.getAction())) {
                int moduleState = intent.getIntExtra(Constant.EXTRA_RESPONSE_DATA, -1);
                if (moduleState == 1) {
                    dmrManager.getDigitalVoiceInfo();
                } else if (moduleState == 2) {
                    updateInfo();
                } else if (moduleState == 3) {
                    SoundPoolUtils.getInstance(MainActivity.this).playSound(true);
                } else if (moduleState == 4) {
                    updateInfo();
                    SoundPoolUtils.getInstance(MainActivity.this).playSound(true);
                }
            }else if (Constant.ACTION_VERSION_INFO.equals(intent.getAction())) {

            }else if (Constant.ACTION_SIGNAL_INFO.equals(intent.getAction())) {

            }else if (Constant.ACTION_INBOUND_TYPE.equals(intent.getAction())) {
               int callType  = intent.getIntExtra(Constant.EXTRA_RESPONSE_DATA, -1);
               mSp.edit().putInt("callType",callType).commit();
                switch (callType) {
                    case 0:
                        tvCallType.setText(getString(R.string.call_single));
                        break;
                    case 1:
                        tvCallType.setText(getString(R.string.call_group));
                        break;
                    case 2:
                        tvCallType.setText(getString(R.string.call_all));
                        break;
                }
            }else if (Constant.ACTION_TRANSMITTER_LOCAL_ID.equals(intent.getAction())) {
               int localId = intent.getIntExtra(Constant.EXTRA_RESPONSE_DATA, -1);
               int type = mSp.getInt("callType",-1);
               if(type == 0){
                   tvContact.setText(localId + "");
               }
            }else if (Constant.ACTION_INBOUND_NUMBER.equals(intent.getAction())) {
                int contact = intent.getIntExtra(Constant.EXTRA_RESPONSE_DATA, -1);
                int type = mSp.getInt("callType",-1);
                if(type == 1 || type == 2){
                    tvContact.setText(contact + "");
                }

            }else if (Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) {
                if (1 == intent.getIntExtra("state", 0)) {
                    isHeadSet = true;
                } else if (0 == intent.getIntExtra("state", 0)) {
                    isHeadSet = false;
                }
                Log.d(TAG, "isHeadSet=" + isHeadSet);
            }
        }
    };


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        long secondTime = System.currentTimeMillis();
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (secondTime - firstTime < 2000) {
                dmrManager.setMode(1);
                finish();
            } else {
                Toast.makeText(MainActivity.this, getString(R.string.press_again_back), Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public String  getIMEI(Context context) {
        try {

            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},100);
            }
            @SuppressLint("HardwareIds")
            String imei = telephonyManager.getDeviceId();
            if (imei == null) {
                return null;
            }
            Log.d(TAG,"imei="+imei);
            return imei;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return super.onKeyUp(keyCode, event);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        String imei = getIMEI(this);
        Log.d(TAG,"imei="+imei);
    }
}
